package com.bootdo.app.common.utils;

import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.io.IOException;
import java.security.SecureRandom;

/**
  * @auther: Along
  * @description: DES 加密工具类
  */
public class DesUtil {

    private final static String DES = "DES";
    private static char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
            '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
    private static String charset = "UTF-8";


    /**
     * 字节转换成 16 进制字符串
     * @param b
     * @return
     */
    public static String byteToHex(byte[] b) {
        int len = b.length;
        char str[] = new char[len * 2];
        int k = 0;
        for (int i = 0; i < len; i++) {
            byte byte0 = b[i];
            str[k++] = hexDigits[byte0 >>> 4 & 0xf];
            str[k++] = hexDigits[byte0 & 0xf];
        }
        return new String(str);
    }

    /**
     * DES 加密 ：字符串以UTF-8编码加密, 并进行Base64Encode
     *
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static String desEncryptStr_UTF8(String data, byte[] key) throws Exception {
        if (data == null)
            return null;
        byte[] encryptDes = encrypt_des(data.getBytes(charset), key);
        String str = Base64.encodeBase64String(encryptDes);
        str = str.replace("+", "_").replace("/", "-").replace("=", "^");
        return str;
    }

    /**
     * DES 解密 ：先Base64Decode 字符串, 再解密,返回UTF-8
     *
     * @param data
     * @param key
     * @return
     * @throws IOException
     * @throws Exception
     */
    public static String desDecryptStr_UTF8(String data, byte[] key) throws IOException, Exception {
        if (data == null)
            return null;
        data = data.replace("_", "+").replace("-", "/").replace("^", "=");
        byte[] decodeBase64 = Base64.decodeBase64(data);
        byte[] deced = decrypt_des(decodeBase64, key);
        return new String(deced,charset);
    }

    /**
     * DES 加密
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] encrypt_des(byte[] data, byte[] key) throws Exception {
        // 生成一个可信任的随机数源
        SecureRandom secureRandom = new SecureRandom();
        // 从原始密钥数据创建DESKeySpec对象
        DESKeySpec desKeySpec = new DESKeySpec(key);
        // 创建一个密钥工厂，然后用它把DESKeySpec转换成SecretKey对象
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
        SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
        // Cipher对象实际完成加密操作
        Cipher cipher = Cipher.getInstance(DES);
        // 用密钥初始化Cipher对象
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, secureRandom);
        return cipher.doFinal(data);
    }

    /**
     * DES 解密
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] decrypt_des(byte[] data, byte[] key) throws Exception {
        // 生成一个可信任的随机数源
        SecureRandom secureRandom = new SecureRandom();
        // 从原始密钥数据创建DESKeySpec对象
        DESKeySpec desKeySpec = new DESKeySpec(key);
        // 创建一个密钥工厂，然后用它把DESKeySpec转换成SecretKey对象
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
        SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
        // Cipher对象实际完成解密操作
        Cipher cipher = Cipher.getInstance(DES);
        // 用密钥初始化Cipher对象
        cipher.init(Cipher.DECRYPT_MODE, secretKey, secureRandom);
        return cipher.doFinal(data);
    }

    public static void main(String[] args) throws Exception {

        // 测试 des 加解密
        String str = "123465";
        byte[] key = "sadadasdad".getBytes();
        // des加密
        final byte[] encrypt_des = encrypt_des(str.getBytes(charset), key);
        // des解密
        final byte[] decrypt_des = decrypt_des(encrypt_des, key);
        System.out.println("密文解密结果 = " + new String(decrypt_des,charset));

        // 测试 des & base64加解密
        System.out.println("---------------------");

        final String encryptStr = desEncryptStr_UTF8(str, key);
        System.out.println("des加密并base64-密文 = " + encryptStr);

        final String decryptStr = desDecryptStr_UTF8(encryptStr, key);
        System.out.println("des解密密文 result = " + decryptStr);


        // 测试16进制转换
        System.out.println("------------");

        final String s1 = byteToHex("a".getBytes()); // a : 97
        System.out.println("s1 = " + s1);
    }


}
